package idv.arthur.jenkins;

import idv.arthur.widgets.Widgets;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jvnet.hudson.client_demo.URLConnectionUtil;

public class JobDepStruc {

	private static boolean isNotContain = true;
	public JobDepStruc(String modId) {
		this.modId = modId;
	}
	
	private JobDepStruc up = null;
	private String modId;
	private ArrayList<JobDepStruc> down =null;
	private int nextBuildNumber;
	private boolean isLeaf = false;
	
	
	public boolean isLeaf() {
		return isLeaf;
	}
	public void setLeaf(boolean isLeaf) {
		this.isLeaf = isLeaf;
	}
	
	public static boolean isNotContain() {
		return isNotContain;
	}
	public static void setNotContain(boolean isNotContain) {
		JobDepStruc.isNotContain = isNotContain;
	}
	public int getNextBuildNumber() {
		return nextBuildNumber;
	}
	public void setNextBuildNumber(int nextBuildNumber) {
		this.nextBuildNumber = nextBuildNumber;
	}
	public JobDepStruc getUp() {
		return up;
	}
	public void setUp(JobDepStruc up) {
		this.up = up;
	}
	public ArrayList<JobDepStruc> getDown() {
		return down;
	}
	public void setDown(ArrayList<JobDepStruc> down) {
		this.down = down;
	}
	public String getModId() {
		return modId;
	}
	public void setModId(String modId) {
		this.modId = modId;
	}
	public boolean isContain(JobDepStruc obj,String modId) {
		if ( modId.equalsIgnoreCase(this.modId) ) {
			isNotContain = false;
		} else {
			for(int i=0; i<obj.getDown().size();i++){
				isNotContain = !obj.getDown().get(i).isContain(obj.getDown().get(i),modId);
			}
		}
		
		return !isNotContain;
	}
	
	
	/**
	 * 	取得這個模組一下次jenkins執行的job號
	 *	@return
	 *	@throws IOException	
	 *	<br>創建時間：2013/11/22 上午11:02:40<br>
	 *	創建人員：郭啟揚 (842297)
	 */
	public int nextBuildNumber() throws IOException {
		final Widgets wid = new Widgets();
		int nextBuildNumber = 0;
		String urlStr = wid.JENKINSURL+"job/"+this.getModId()+"/api/xml";
		// 連線取得資料
        InputStream res = null; 
        final SAXReader reader = new SAXReader();
        final Map<String,Object> map = new HashMap<String,Object>();
        try {
        	res = URLConnectionUtil.doGet(urlStr,false,wid.JENKINS_USR,wid.JENKINS_PWD,map);
        	final Document document = reader.read(res);
    		Element root = document.getRootElement();
    		Iterator<Element> it = root.elementIterator();	
        	while (it.hasNext()) {
    			Element e2 = it.next();
    			if ( "nextBuildNumber".equalsIgnoreCase(e2.getName() ) ) {
    				nextBuildNumber = Integer.parseInt(e2.getText());
    			}
    		}
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
        	res.close();
        }
        
        return nextBuildNumber;
	}

}
